package com.badboy.servlet;

import com.badboy.entity.Posts;
import com.badboy.mapper.PostsMapper;
import com.badboy.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/PostServlet")
public class PostServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String action = request.getParameter("action");
        PrintWriter out = response.getWriter();

        if (!"createPost".equals(action)) {
            out.write("{\"success\":false,\"message\":\"无效的操作\"}");
            return;
        }

        SqlSession sqlSession = null;
        try {
            // 创建实体对象
            Posts post = new Posts();
            post.setTitle(request.getParameter("title"));
            post.setContent(request.getParameter("content"));
            Integer id = Integer.parseInt(request.getParameter("userId"));
            post.setUserId(id);
            post.setForumId(Integer.parseInt(request.getParameter("forumId")));
            post.setCreatedAt(new java.util.Date());

            // 数据库操作
            sqlSession = MyBatisUtil.getSqlSession();
            PostsMapper postsMapper = sqlSession.getMapper(PostsMapper.class);
            int result = postsMapper.insertSelective(post);

            if (result > 0) {
                sqlSession.commit(); // 提交事务
                out.write("{\"success\":true,\"message\":\"发帖成功\"}");
            } else {
                sqlSession.rollback(); // 回滚事务
                out.write("{\"success\":false,\"message\":\"发帖失败\"}");
            }
        } catch (Exception e) {
            if (sqlSession != null) {
                sqlSession.rollback(); // 异常时回滚
            }
            out.write("{\"success\":false,\"message\":\"系统错误: " + e.getMessage() + "\"}");
            e.printStackTrace(); // 实际项目中应该使用日志记录
        } finally {
            if (sqlSession != null) {
                sqlSession.close(); // 确保关闭session
            }
        }
    }
}
